<?php
/**
 * CSV关键词批量导入页面
 */
require_once __DIR__ . '/classes/Database.php';
require_once __DIR__ . '/classes/Logger.php';

// 加载配置文件
$config = require __DIR__ . '/config/config.php';
$logger = new Logger($config);

$message = '';
$messageType = '';
$stats = [];

// 处理文件上传
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    try {
        $logger->info('=== 开始CSV导入 ===');
        
        // 检查文件是否上传成功
        if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('文件上传失败，错误代码: ' . $_FILES['csv_file']['error']);
        }
        
        $filePath = $_FILES['csv_file']['tmp_name'];
        $fileName = $_FILES['csv_file']['name'];
        
        $logger->info('接收到文件', ['name' => $fileName, 'size' => $_FILES['csv_file']['size']]);
        
        // 检查文件扩展名
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if ($fileExt !== 'csv') {
            throw new Exception('只支持CSV文件格式');
        }
        
        // 打开CSV文件
        $handle = fopen($filePath, 'r');
        if ($handle === false) {
            throw new Exception('无法读取CSV文件');
        }
        
        // 跳过标题行（第一行）
        fgetcsv($handle);
        
        $db = Database::getInstance();
        $totalRows = 0;
        $successRows = 0;
        $errorRows = 0;
        $batchSize = 1000;
        $batch = [];
        $lineNumber = 1; // 从第2行开始（A2）
        
        $logger->info('开始读取CSV数据');
        
        // 逐行读取CSV
        while (($data = fgetcsv($handle)) !== false) {
            $lineNumber++;
            $totalRows++;
            
            // A列：keyword, B列：type
            $keyword = isset($data[0]) ? trim($data[0]) : '';
            $type = isset($data[1]) ? trim($data[1]) : '';
            
            // 验证数据
            if (empty($keyword)) {
                $logger->warning('跳过空关键词', ['line' => $lineNumber]);
                $errorRows++;
                continue;
            }
            
            // 添加到批处理数组
            $batch[] = [
                'keyword' => $keyword,
                'type' => $type
            ];
            
            // 当批处理数组达到1000条时，执行批量插入
            if (count($batch) >= $batchSize) {
                $inserted = batchInsertKeywords($db, $batch, $logger);
                $successRows += $inserted;
                $logger->info('批量插入完成', [
                    'batch_size' => count($batch),
                    'inserted' => $inserted,
                    'total_success' => $successRows
                ]);
                $batch = []; // 清空批处理数组
            }
        }
        
        // 插入剩余的数据
        if (count($batch) > 0) {
            $inserted = batchInsertKeywords($db, $batch, $logger);
            $successRows += $inserted;
            $logger->info('最后批次插入完成', [
                'batch_size' => count($batch),
                'inserted' => $inserted
            ]);
        }
        
        fclose($handle);
        
        $stats = [
            'total' => $totalRows,
            'success' => $successRows,
            'error' => $errorRows
        ];
        
        $logger->info('=== CSV导入完成 ===', $stats);
        
        $message = "导入完成！总行数: {$totalRows}, 成功: {$successRows}, 失败: {$errorRows}";
        $messageType = 'success';
        
    } catch (Exception $e) {
        $logger->error('CSV导入失败', ['error' => $e->getMessage()]);
        $message = '导入失败: ' . $e->getMessage();
        $messageType = 'error';
    }
}

/**
 * 批量插入关键词
 */
function batchInsertKeywords($db, $batch, $logger) {
    if (empty($batch)) {
        return 0;
    }
    
    try {
        // 构建批量插入SQL
        $sql = "INSERT INTO keyword (type, keyword, add_time, update_time) VALUES ";
        $values = [];
        $params = [];
        
        foreach ($batch as $item) {
            $values[] = "(?, ?, NOW(), NOW())";
            $params[] = $item['type'];
            $params[] = $item['keyword'];
        }
        
        $sql .= implode(', ', $values);
        
        // 执行批量插入
        $db->query($sql, $params);
        
        return count($batch);
        
    } catch (Exception $e) {
        $logger->error('批量插入失败', ['error' => $e->getMessage()]);
        throw $e;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV关键词批量导入</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            padding: 40px;
            max-width: 600px;
            width: 100%;
        }
        
        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
        }
        
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            background: #f8f9ff;
            margin-bottom: 20px;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .upload-area:hover {
            border-color: #764ba2;
            background: #f0f2ff;
        }
        
        .upload-area.dragover {
            border-color: #764ba2;
            background: #e8ebff;
        }
        
        .upload-icon {
            font-size: 48px;
            margin-bottom: 10px;
        }
        
        input[type="file"] {
            display: none;
        }
        
        .file-name {
            margin-top: 15px;
            color: #667eea;
            font-weight: 500;
        }
        
        .btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .stats {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .stats h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 18px;
        }
        
        .stat-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e9ecef;
        }
        
        .stat-item:last-child {
            border-bottom: none;
        }
        
        .stat-label {
            color: #666;
        }
        
        .stat-value {
            font-weight: 600;
            color: #333;
        }
        
        .instructions {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .instructions h3 {
            color: #856404;
            margin-bottom: 10px;
            font-size: 16px;
        }
        
        .instructions ul {
            color: #856404;
            margin-left: 20px;
            font-size: 14px;
        }
        
        .instructions li {
            margin: 5px 0;
        }
        
        .back-link {
            display: inline-block;
            margin-top: 20px;
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
        }
        
        .back-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📥 批量导入关键词</h1>
        <p class="subtitle">上传CSV文件，批量导入关键词到数据库</p>
        
        <div class="instructions">
            <h3>📋 使用说明</h3>
            <ul>
                <li>第一行为标题行（将被忽略）</li>
                <li><strong>A列</strong>：关键词（keyword）</li>
                <li><strong>B列</strong>：类型（type）</li>
                <li>从第2行（A2）开始读取数据</li>
                <li>每1000行批量插入一次</li>
                <li>自动设置添加时间和更新时间</li>
            </ul>
        </div>
        
        <?php if ($message): ?>
            <div class="message <?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($stats)): ?>
            <div class="stats">
                <h3>📊 导入统计</h3>
                <div class="stat-item">
                    <span class="stat-label">总行数</span>
                    <span class="stat-value"><?php echo $stats['total']; ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">成功导入</span>
                    <span class="stat-value" style="color: #28a745;"><?php echo $stats['success']; ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">失败/跳过</span>
                    <span class="stat-value" style="color: #dc3545;"><?php echo $stats['error']; ?></span>
                </div>
            </div>
        <?php endif; ?>
        
        <form method="POST" enctype="multipart/form-data" id="uploadForm">
            <div class="upload-area" id="uploadArea" onclick="document.getElementById('csvFile').click()">
                <div class="upload-icon">📄</div>
                <p style="color: #666; margin-bottom: 10px;">点击选择CSV文件或拖拽文件到这里</p>
                <p style="color: #999; font-size: 12px;">支持的格式: .csv</p>
                <div class="file-name" id="fileName"></div>
            </div>
            
            <input type="file" 
                   name="csv_file" 
                   id="csvFile" 
                   accept=".csv"
                   required
                   onchange="handleFileSelect(this)">
            
            <button type="submit" class="btn" id="uploadBtn" disabled>
                📤 开始导入
            </button>
        </form>
        
        <a href="index.php" class="back-link">← 返回首页</a>
    </div>
    
    <script>
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('csvFile');
        const fileName = document.getElementById('fileName');
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadForm = document.getElementById('uploadForm');
        
        // 文件选择处理
        function handleFileSelect(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                fileName.textContent = '已选择: ' + file.name;
                uploadBtn.disabled = false;
            }
        }
        
        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                handleFileSelect(fileInput);
            }
        });
        
        // 表单提交处理
        uploadForm.addEventListener('submit', (e) => {
            uploadBtn.disabled = true;
            uploadBtn.textContent = '⏳ 正在导入，请稍候...';
        });
    </script>
</body>
</html>

